package com.whfc.quality.service.impl;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.whfc.base.param.AppFileExportParam;
import com.whfc.base.service.AppExportService;
import com.whfc.common.exception.BizException;
import com.whfc.common.file.FileHandler;
import com.whfc.common.file.FilePathConfig;
import com.whfc.common.file.properties.FileExpirationRules;
import com.whfc.common.result.PageData;
import com.whfc.common.result.ResultEnum;
import com.whfc.common.util.*;
import com.whfc.fuum.service.SysDeptService;
import com.whfc.quality.dao.QualityRectifyDetailsMapper;
import com.whfc.quality.dao.QualityRectifyInfoMapper;
import com.whfc.quality.dto.QualityCheckDTO;
import com.whfc.quality.dto.QualityRectifyDTO;
import com.whfc.quality.entity.QualityRectifyInfo;
import com.whfc.quality.param.QualityRectifyAddParam;
import com.whfc.quality.param.QualityRectifyEditParam;
import com.whfc.quality.service.QualityRectifyService;
import org.apache.commons.lang3.StringUtils;
import org.apache.dubbo.config.annotation.DubboReference;
import org.apache.dubbo.config.annotation.DubboService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.ClassPathResource;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import javax.annotation.PostConstruct;
import java.io.*;
import java.util.Date;
import java.util.List;
import java.util.concurrent.CompletableFuture;

/**
 * @author: hw
 * @date: 2021-10-18 17:41
 * @description: 质量整改单
 */
@DubboService(interfaceClass = QualityRectifyService.class, version = "1.0.0")
public class QualityRectifyServiceImpl implements QualityRectifyService {

    private Logger logger = LoggerFactory.getLogger(this.getClass());

    @Autowired
    private QualityRectifyInfoMapper qualityRectifyInfoMapper;

    @Autowired
    private QualityRectifyDetailsMapper qualityRectifyDetailsMapper;

    @DubboReference(interfaceClass = SysDeptService.class, version = "1.0.0")
    private SysDeptService sysDeptService;

    @DubboReference(interfaceClass = AppExportService.class, version = "1.0.0")
    private AppExportService appExportService;


    @Autowired
    private FilePathConfig msFilePathConfig;

    @Autowired
    private FileHandler fileHandler;

    private JSONObject pdfConfig;

    private final static String EXPORT_IMG_TEMPLATE = "<img src='%s' />";

    private final static String QUALITY_FILE_DESC = "质量整改通知单导出";

    private final static String HTML_TEMPLATE_PATH = "pdfTemp/qualityRectifyTemp.html";

    private final static String PDF_CONFIG_PATH = "pdfConfig/config.json";

    @PostConstruct
    public void info() throws IOException {
        ClassPathResource resource = new ClassPathResource(PDF_CONFIG_PATH);
        InputStream templateFileInputStream = resource.getInputStream();
        String pdfConfigStr = new String(FileUtil.readData(templateFileInputStream));
        if (StringUtils.isNotEmpty(pdfConfigStr)) {
            pdfConfig = JSONObject.parseObject(pdfConfigStr);
        }
    }

    @Override
    public PageData<QualityRectifyDTO> list(Integer deptId, Date startTime, Date endTime, Integer pageNum, Integer pageSize) throws BizException {
        logger.info("整改通知单列表,deptId：{},startTime：{},endTime：{},pageNum：{},pageSize：{}", deptId, startTime, endTime, pageNum, pageSize);
        PageHelper.startPage(pageNum, pageSize);
        List<QualityRectifyDTO> list = qualityRectifyInfoMapper.selectByDeptId(deptId, startTime, endTime);
        for (QualityRectifyDTO v : list) {
            Integer questionNum = qualityRectifyDetailsMapper.selectCountByRectifyId(v.getRectifyId());
            v.setQuestionNum(questionNum);
        }
        PageHelper.clearPage();
        return PageUtil.pageData(PageInfo.of(list));
    }

    @Override
    public PageData<QualityCheckDTO> details(Integer rectifyId, Integer pageNum, Integer pageSize) throws BizException {
        logger.info("整改通知单详情(分页),rectifyId：{},pageNum：{},pageSize：{}", rectifyId, pageNum, pageSize);
        PageHelper.startPage(pageNum, pageSize);
        List<QualityCheckDTO> list = qualityRectifyDetailsMapper.selectByRectifyId(rectifyId);
        PageHelper.clearPage();
        return PageUtil.pageData(PageInfo.of(list));
    }

    @Override
    public List<QualityCheckDTO> details(Integer rectifyId) throws BizException {
        logger.info("整改通知单详情(不分页),rectifyId：{}", rectifyId);
        return qualityRectifyDetailsMapper.selectByRectifyId(rectifyId);
    }

    @Override
    public void add(QualityRectifyAddParam param) throws BizException {
        logger.info("添加整改通知单,param:{}", param);
        QualityRectifyInfo record = new QualityRectifyInfo();
        record.setQuestionNum(param.getCheckIds().size());
        BeanUtils.copyProperties(param, record);
        qualityRectifyInfoMapper.insertSelective(record);
        qualityRectifyDetailsMapper.insertAll(record.getId(), param.getCheckIds());
    }

    @Override
    public void edit(QualityRectifyEditParam param) throws BizException {
        QualityRectifyInfo record = qualityRectifyInfoMapper.selectByPrimaryKey(param.getRectifyId());
        if (record == null) {
            throw new BizException(ResultEnum.NOT_FOUND.getCode(), "未找到该整改单信息");
        }
        qualityRectifyDetailsMapper.delByRectifyId(record.getId());
        BeanUtils.copyProperties(param, record);
        qualityRectifyInfoMapper.updateByPrimaryKeySelective(record);
        qualityRectifyDetailsMapper.insertAll(record.getId(), param.getCheckIds());
    }

    @Override
    public void del(Integer rectifyId) throws BizException {
        logger.info("删除整改通知单,rectifyId:{}", rectifyId);
        qualityRectifyDetailsMapper.delByRectifyId(rectifyId);
        qualityRectifyInfoMapper.del(rectifyId);
    }

    @Override
    public void export(Integer rectifyId) throws BizException {
        logger.info("导出整改通知单,rectifyId:{}", rectifyId);
        QualityRectifyInfo rectifyInfo = qualityRectifyInfoMapper.selectByPrimaryKey(rectifyId);


        String fileDesc = QUALITY_FILE_DESC;
        String fileName = RandomUtil.getRandomFileName();
        String suffix = "pdf";
        AppFileExportParam fileExport = new AppFileExportParam();
        fileExport.setDeptId(rectifyInfo.getDeptId());
        fileExport.setFileName(fileName);
        fileExport.setFileFormat(suffix.toUpperCase());
        fileExport.setFileState(0);
        fileExport.setFileDesc(fileDesc);
        Integer id = appExportService.install(fileExport);
        fileExport.setId(id);
        CompletableFuture.supplyAsync(() -> {
            String companyName = null;
            String footer = null;
            String header = null;
            if (pdfConfig.containsKey(rectifyInfo.getDeptId().toString())) {
                JSONObject config = pdfConfig.getJSONObject(rectifyInfo.getDeptId().toString());
                companyName = config.getString("companyName");
                footer = config.getString("footer");
                header = config.getString("header");
            }
            String deptName = sysDeptService.getDeptName(rectifyInfo.getDeptId());
            String timeStr = DateUtil.formatDate(rectifyInfo.getCreateTime(), DateUtil.DATE_FORMAT);
            String[] times = timeStr.split("-");
            JSONObject jsonObject = new JSONObject();
            jsonObject.put("companyName", companyName);
            jsonObject.put("deptName", deptName);
            jsonObject.put("corpName", rectifyInfo.getCorpName());
            jsonObject.put("years", times[0]);
            jsonObject.put("month", times[1]);
            jsonObject.put("day", times[2]);
            List<QualityCheckDTO> list = qualityRectifyDetailsMapper.selectByRectifyId(rectifyId);
            jsonObject.put("checkList", JSONArray.parseArray(JSONUtil.toString(list)));
            ClassPathResource resource = new ClassPathResource(HTML_TEMPLATE_PATH);
            String html;
            try {
                logger.debug("开始生成文件");
                InputStream templateFileInputStream = resource.getInputStream();
                File tempFile = FileUtil.copyTemplateFile(templateFileInputStream);
                html = HtmlUtil.freeMarkerRender(jsonObject, tempFile);
                ByteArrayOutputStream arrayOutputStream = ItextPdfUtil.htmlToPdf(html, header, footer);
                InputStream is = new ByteArrayInputStream(arrayOutputStream.toByteArray());
                templateFileInputStream.close();
                logger.debug("文件生成完成,开始上传文件");
                String path = msFilePathConfig.getFilePath("quality/export", fileName, suffix);
                String upload = fileHandler.upload(path, is, FileExpirationRules.DAYS_7);
                fileExport.setFileUrl(upload);
                fileExport.setFileState(1);
                appExportService.update(fileExport);
            } catch (IOException e) {
                e.printStackTrace();
                logger.error("质量pdf导出异常", e);
            }

            return null;
        });
    }

    @Transactional
    @Override
    public void deleteBatch(List<Integer> idList) {
        if(CollectionUtils.isEmpty(idList)){
            return;
        }
        qualityRectifyInfoMapper.deleteBatch(idList);
        qualityRectifyDetailsMapper.deleteBatchByRectifyId(idList);
    }
}
